export function formatSongInfoFn(songInfo) {
  let formatSongInfo = {};
  switch (songInfo.platform) {
    case 'bili':
      formatSongInfo = {
        platform: 'bili',
        id: new Date().getTime(),
        author: songInfo.author,
        bvid: songInfo.bvid,
        pic: songInfo.pic,
        title: songInfo.title,
        link: songInfo.link,
      };
      break;
  }
  return formatSongInfo;
}

export const getSongMenuNameList = () => {
  return localStorage.getObject('songMenu').map((item) => {
    return item.menuName;
  });
};

export const joinSongMenu = (menuName, songInfo) => {
  const formatSongInfo = formatSongInfoFn(songInfo);
  const songMenu = localStorage.getObject('songMenu') || [];
  const targetMenu = songMenu.find((item) => item.menuName === menuName);
  const exists = targetMenu.songList.some((item) => item.title === formatSongInfo.title && item.author === formatSongInfo.author);
  if (!exists) {
    targetMenu.songList.push(formatSongInfo);
    localStorage.setObject('songMenu', songMenu);
  }
};

export const getSongList = (menuName) => {
  return localStorage.getObject('songMenu').find((item) => item.menuName === menuName).songList;
};

export const setSongList = (menuName, list) => {
  const songMenu = localStorage.getObject('songMenu') || [];
  const targetMenu = songMenu.find((item) => item.menuName === menuName);
  targetMenu.songList = list;
  localStorage.setObject('songMenu', songMenu);
};

export const editMenuInfo = ({ editMenuOldName, editMenuNewName, editImgUrl }) => {
  const songMenu = localStorage.getObject('songMenu') || [];
  const targetMenu = songMenu.find((item) => item.menuName === editMenuOldName);
  targetMenu.menuName = editMenuNewName;
  targetMenu.menuImg = editImgUrl;
  localStorage.setObject('songMenu', songMenu);
};

export const deleteMenu = (menuName) => {
  const songMenu = localStorage.getObject('songMenu') || [];
  const index = songMenu.findIndex((item) => item.menuName === menuName);
  if (index !== -1) {
    songMenu.splice(index, 1);
    localStorage.setObject('songMenu', songMenu);
  }
};

export const getMenuImg = (menuName) => {
  const songMenu = localStorage.getObject('songMenu') || [];
  const targetMenu = songMenu.find((item) => item.menuName === menuName);
  return targetMenu.menuImg;
};
